package com.chj.comp.common.help.util;

import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import java.util.Base64;

/**
 * 默认加密规则
 * 用户密码加密/client_secret加密
 * @author ：cuihui
 * @date ：Created in 2022/2/17
 * @description：SpringSecurity密码生成
 * @modified By：
 */
public class SecurityPwdUtil {

    private static BCryptPasswordEncoder bcryptPasswordEncoder = new BCryptPasswordEncoder();

    /**
     * 密码加密
     * @param passwd
     * @return
     */
    public static String encodeStr(String passwd){
        String hashPass = bcryptPasswordEncoder.encode(passwd);
        return hashPass;
    }

    /**
     * 校验明文密码、密文密码是否匹配
     * @param rawPasswd 明文密码
     * @param encodePasswd 密文密码
     * @return
     */
    public static boolean matches(String rawPasswd, String encodePasswd){
        return bcryptPasswordEncoder.matches(rawPasswd,encodePasswd);
    }

    /**
     * 生成basic auth
     * 规则：client_id:client_secret 生成base64字符串
     * @param clientId
     * @param clientSecret
     * @return
     */
    public static String generateBasicAuth(String clientId, String clientSecret){
        return Base64.getEncoder().encodeToString((clientId + ":" + clientSecret).getBytes());
    }

    public static void main(String[] args) {
        // 生成密文
        String passwd = "blmp@2022";
        String encodeStr = SecurityPwdUtil.encodeStr(passwd);
        System.out.println(encodeStr);

        // 校验明文密文（加密是不可逆的，只能校验）
        boolean f1 = SecurityPwdUtil.matches("Gs279727","$2a$10$HdK2EKMtKFU1kpHhTMRFoupQkYSR35qfLddac790HVWOVivwFYTIK");
        boolean f2 = SecurityPwdUtil.matches("secret","$2a$10$FyOVE7qV9e2/kHnnRUGOJeK7/9WP4ZZIYB9VlFTX1M/p/6lvrbm/u");
        System.out.println("password----->" + f1);
        System.out.println("secret----->" + f2);

        // 生成basic auth
        String basic = SecurityPwdUtil.generateBasicAuth("c1", "secret");
        System.out.println("basic----->" + basic);
    }
}
